// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
const _=db.command;
const $ = db.command.aggregate;
// 云函数入口函数
exports.main = async (event, context) => {

 var type=event.type?event.type:""
  //获取排行榜

  if(type=="top"){
    return await db.collection("xcmall_product").where({
      checked:true
    }).orderBy("sales","desc").limit(6).get()
  }

  if(type=="banner"){
    return await db.collection("xcmall_product").where({
      checked:true,
      recommend:true
    }).orderBy("_updateTime","desc").limit(4).get()
  }

  var sql;
  if(type=="category"){
    //查询tabbar分类列表的详情
    return await db.collection("xcmall_classify").aggregate()
    .lookup({
      from:"xcmall_product",
      let:{
        class_id:"$_id",
        class_name:"$name"
      },
      pipeline:$.pipeline()
      .match(_.expr($.eq(["$parentid","$$class_id"])))
      .sort({
        orderid:-1
      })
      .done(),//子查询开始
      as:"prolist"
    })
    .end();
  } 

  //查询所有详情分类列表
  return await db.collection("xcmall_classify").aggregate()
  .lookup({
    from:"xcmall_product",
    let:{
      class_id:"$_id",
      class_name:"$name"
    },
    pipeline:$.pipeline()
    .match(_.expr($.eq(["$parentid","$$class_id"])))
    .sort({
      orderid:-1
    })
    .limit(3)
    .done(),//子查询开始
    as:"prolist"
  })
  .end();

}